import 'dart:async';
import 'dart:core';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/notify_bg_music_to_stop_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/position_seek_widget.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/select_smart_home_bgm_event.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

/// 设置设备状态弹窗
class SetSmartHomeFolderBgmDialog extends StatefulWidget {

  final List<MusicListBean> musicList;
  final AssetsAudioPlayer assetsAudioPlayer;
  final String selectId;

  const SetSmartHomeFolderBgmDialog({Key key, this.musicList, this.assetsAudioPlayer, this.selectId}) : super(key: key);

  @override
  _SetSmartHomeFolderBgmDialogState createState() =>
      _SetSmartHomeFolderBgmDialogState();

  ///跳转方法
  static Future<MusicListBean> navigatorPushDialog(BuildContext context,
      List<MusicListBean> musicList, AssetsAudioPlayer assetsAudioPlayer, String selectId) {
    return VgDialogUtils.showCommonBottomDialog<MusicListBean>(
      context: context,
      child: SetSmartHomeFolderBgmDialog(
        musicList:musicList,
        assetsAudioPlayer:assetsAudioPlayer,
        selectId:selectId,
      ),
    );
  }

}

class _SetSmartHomeFolderBgmDialogState extends BaseState<SetSmartHomeFolderBgmDialog> with SingleTickerProviderStateMixin{


  final List<StreamSubscription> _subscriptions = [];
  bool _isPlaying = false;
  Audio _playingAudio;
  String _currentMusicId;
  AssetsAudioPlayer _assetsAudioPlayer;
  String _selectId;
  AnimationController _controller;
  ScrollController _listViewController;
  @override
  void initState() {
    super.initState();
    if(widget?.assetsAudioPlayer == null){
      _assetsAudioPlayer = AssetsAudioPlayer.newPlayer();
    }else{
      _assetsAudioPlayer = widget?.assetsAudioPlayer;
    }
    _listViewController = ScrollController();
    _selectId = widget?.selectId;
    _subscriptions.add(_assetsAudioPlayer.onReadyToPlay.listen((event) {
      VgHudUtils.hide(context);
    }));
    _subscriptions.add(_assetsAudioPlayer.playlistAudioFinished.listen((data) {
      print('playlistAudioFinished : $data');
    }));
    _subscriptions.add(_assetsAudioPlayer.audioSessionId.listen((sessionId) {
      print('audioSessionId : $sessionId');
    }));
    _subscriptions.add(_assetsAudioPlayer.isPlaying.listen((isPlay) {
      setState(() {
        _isPlaying = isPlay??false;
      });
    }));
    _subscriptions.add(_assetsAudioPlayer.current.listen((playing) {
      if(playing != null){
        setState(() {
          _currentMusicId = playing?.audio?.audio?.metas?.id??"";
          print('_currentMusicId : $_currentMusicId');
        });
      }
    }));

    _controller = AnimationController(duration: const Duration(seconds: 1), vsync: this);
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画从 controller.forward() 正向执行 结束时会回调此方法
        //重置起点
        _controller.reset();
        //开启
        _controller.forward();
      } else if (status == AnimationStatus.dismissed) {
        //动画从 controller.reverse() 反向执行 结束时会回调此方法
      } else if (status == AnimationStatus.forward) {
        //执行 controller.forward() 会回调此状态
      } else if (status == AnimationStatus.reverse) {
        //执行 controller.reverse() 会回调此状态
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Future.delayed(Duration(milliseconds: 1), () {
        double listHeight = ScreenUtils.screenH(context)/2 - 14;
        for(int i = 0; i < (widget?.musicList?.length??0); i++){
          if(widget?.musicList?.elementAt(i)?.id == _selectId){
            if(50.0 * (i+1) >listHeight){
              _listViewController.jumpTo(50.0 * (i+1));
            }
          }
        }
      });

    });
  }
  
  @override
  void dispose() {
    _subscriptions?.clear();
    _controller?.dispose();
    if(widget?.assetsAudioPlayer == null){
      _assetsAudioPlayer?.stop();
      _assetsAudioPlayer?.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      child: Container(
        constraints: BoxConstraints(
          maxHeight: ScreenUtils.screenH(context)/2,
        ),
        decoration: BoxDecoration(
            color: Colors.white
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(height: 10,),
            Container(
              width: 31,
              height: 4,
              decoration: BoxDecoration(
                color: Color(0XFFD8D8D8),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            _toListPage(),
          ],
        ),
      ),
    );
  }

  Widget _toListPage(){
    return Expanded(
      child: ListView.separated(
          padding: EdgeInsets.only(
              left: 0,
              right: 0,
              top: 0,
              bottom: ScreenUtils.getBottomBarH(context)
          ),
          controller: _listViewController,
          itemCount: widget?.musicList?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (BuildContext context, int index) {
            return _toListItemWidget(index, widget?.musicList?.elementAt(index));
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(height: 0);
          }),
    );
  }

  Widget _toListItemWidget(int index, MusicListBean itemBean){
    return Column(
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            openPlayer(itemBean);
          },
          child: Container(
            height: 60,
            padding: EdgeInsets.symmetric(horizontal: 15),
            alignment: Alignment.centerLeft,
            color: Colors.white,
            child: Row(
              children: [
                _toMusicLogoWidget(itemBean),
                SizedBox(width: 12,),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      width: ScreenUtils.screenW(context) - 200,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        itemBean?.mname??"-",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 15,
                            color: ThemeRepository.getInstance().getCardBgColor_21263C()
                        ),
                      ),
                    ),
                    SizedBox(height: 2,),
                    Text(
                      itemBean?.mtime??"",
                      style: TextStyle(
                          fontSize: 12,
                          color: Color(0XFF8B93A5)
                      ),
                    ),
                  ],
                ),
                Spacer(),
                _toPlayStatusWidget(itemBean),
                SizedBox(width: 10,),
                _toUseWidget(itemBean),
              ],
            ),
          ),
        ),
        _toSeekWidget(itemBean),
      ],
    );
  }

  Widget _toMusicLogoWidget(MusicListBean itemBean){
    if(_isPlaying && itemBean.id == _currentMusicId){
      _controller.forward();
      return RotationTransition(
        alignment: Alignment.center,
        turns: _controller,
        child: Image.asset(
          "images/icon_smart_home_bgm.png",
          width: 44,
          height: 44,
        ),
      );
    }else{
      return Image.asset(
        "images/icon_smart_home_bgm.png",
        width: 32,
        height: 32,
      );
    }
  }

  Widget _toSeekWidget(MusicListBean itemBean){
    return Visibility(
      visible: _isPlaying && itemBean.id == _currentMusicId,
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        child: _assetsAudioPlayer.builderRealtimePlayingInfos(
            builder: (context, infos) {
              if (infos == null) {
                return SizedBox();
              }
              return Column(
                children: [
                  PositionSeekWidget(
                    currentPosition: infos.currentPosition,
                    gradientColorList: [
                      ThemeRepository.getInstance().getCardBgColor_21263C(),
                      ThemeRepository.getInstance().getCardBgColor_21263C(),
                    ],
                    indicatorColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    inactiveTrackColor:Color(0XFFF2F3F4),
                    activeTrackColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    duration: infos.duration,
                    seekTo: (to) {
                      _assetsAudioPlayer.seek(to);
                    },
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          durationToString(infos.currentPosition),
                          style: TextStyle(
                              fontSize: 10,
                              color: ThemeRepository.getInstance().getCardBgColor_21263C()
                          ),
                        ),
                        Spacer(),
                        Text(
                          durationToString(infos.duration),
                          style: TextStyle(
                              fontSize: 10,
                              color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              );
            }),
      ),
    );
  }

  String durationToString(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes =
    twoDigits(duration.inMinutes.remainder(Duration.minutesPerHour));
    String twoDigitSeconds =
    twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }

  Widget _toPlayStatusWidget(MusicListBean itemBean){
    String asset = "images/icon_smart_home_play.png";
    if(_isPlaying && _currentMusicId == (itemBean?.id??"")){
      asset = "images/icon_smart_home_pause.png";
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        openPlayer(itemBean);
      },
      child: Container(
        width: 28,
        height: 28,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(14),
          color: Color(0XFFF2F3F4),
        ),
        child: Image.asset(
          asset,
          width: 14,
          height: 14,
        ),
      ),
    );
  }

  Widget _toUseWidget(MusicListBean itemBean){
    if(itemBean?.id == _selectId){
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          setState(() {
            VgEventBus.global.send(new SelectSmartHomeBgmEvent(null, true));
            if(_currentMusicId == itemBean?.id){
              _assetsAudioPlayer.stop();
            }
            _selectId = "";
          });
        },
        child: Container(
          width: 60,
          height: 28,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
          ),
          child: Text(
            "已使用",
            style: TextStyle(
                fontSize: 13,
                color: Colors.white
            ),
          ),
        ),
      );
    }else{
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          // _viewModel.setBgByHsn(context, widget?.hsn, mid);
          RouterUtils.pop(context, result: itemBean);
        },
        child: Container(
          width: 60,
          height: 28,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            color: Color(0XFFF2F3F4),
          ),
          child: Text(
            "使用",
            style: TextStyle(
                fontSize: 13,
                color: ThemeRepository.getInstance().getCardBgColor_21263C()
            ),
          ),
        ),
      );
    }
  }

  void openPlayer(MusicListBean itemBean) async {
    VgEventBus.global.send(new SelectSmartHomeBgmEvent(itemBean, false));
    VgEventBus.global.send(new NotifyBgMusicToStopEvent(1));
    if(itemBean?.id == _currentMusicId){
      if(_isPlaying){
        _assetsAudioPlayer.pause();
      }else{
        _assetsAudioPlayer.play();
      }
      return;
    }
    VgHudUtils.show(context, "加载中");
    _playingAudio = Audio.network(
        itemBean.murl,
        metas: Metas(
          id: itemBean.id,
          title: itemBean.mname,
          artist: itemBean.author,
          album: itemBean.author,
        ),
        cached: true
    );
    setState(() {});
    try {
      await _assetsAudioPlayer.open(
        _playingAudio,
        autoStart: true,
        showNotification: false,
        loopMode: LoopMode.single,
        playInBackground: PlayInBackground.disabledRestoreOnForeground,
        audioFocusStrategy: AudioFocusStrategy.request(
            resumeAfterInterruption: true,
            resumeOthersPlayersAfterDone: true),
        headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplug,
      );
    } catch (e) {
      print(e);
    }
  }
}
